<template>
    <Card class="no-border-card">
        <!--标题-->
        <p slot="title">
            房源电费信息
        </p>
        <!--标题end-->

        <Row :gutter="20" @keydown.enter.native="initData" class="margin-bottom-20">
            <!-- <i-col span="6">
                <Select clearable v-model="search.type">
                    <Option :value="1">未绑定户号房源</Option>
                    <Option :value="2">已绑定户号房源</Option>
                    <Option :value="3">不可绑定房源</Option>
                </Select>
            </i-col>
            <i-col span="6">
                <Select clearable v-model="search.status">
                    <Option :value="''">选择省市</Option>
                    <Option
                        v-for="option in options"
                        :key="option.id"
                        :value="option.id">{{option.label}}</Option>
                </Select>
            </i-col> -->
            <i-col span="6">
                <Input placeholder="房源地址/房源编号/户号" v-model="search.keyword"></Input>
            </i-col>
            <i-col span="6">
                <i-button @click="initData">搜索</i-button>
            </i-col>
        </Row>

        <Table :loading="loading" :columns="columns" :data="tableData"></Table>

        <Page
            :current.sync="pagination.current"
            :total="pagination.total"
            :page-size="pagination.limit"
            show-total
            style="text-align:center"
            @on-change="initData"></Page>

        <Modal v-model="visible">
            <h4>{{isEdit ? '编辑' : '绑定'}}户号</h4>
            <Form label-position="top" style="padding-top:20px">
                <Spin v-if="loadingIns" fix></Spin>
                <FormItem label="房源地址:">
                    {{currentItem.detail_address}}
                </FormItem>
                <FormItem label="户号:">
                    <i-input v-model="form.home_no"></i-input>
                </FormItem>
                <FormItem label="缴费类型:">
                    <Select v-model="form.sub_biz_type" @on-change="handleBizTypeChange">
                        <Option v-for="type in payType" :key="type.value" :value="type.value">{{type.label}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="选择缴费单位:">
                    <Select v-model="form.chargeInst">
                        <Option
                            v-for="(option, key) in institutions"
                            :key="key"
                            :value="option.chargeInst">{{option.chargeInstName}}</Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="visible = false">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmit">确定</Button>
            </div>
        </Modal>

        <bills-history :home="currentHome" :show.sync="billsVisible"></bills-history>
    </Card>
</template>

<script>
import { mapState } from 'vuex'
import { http, api } from '@/libs/http'
import billsHistory from './components/bills-history.vue'

export default {
  name: 'auto-deduct',
  components: {
    billsHistory
  },
  computed: mapState({
    roleId: state => state.user.roleId
  }),
  /* eslint-disable */
    data() {
        return {
            billsVisible: false,
            currentHome: null,
            loadingIns: false,
            isEdit: false,
            submiting: false,
            visible: false,
            loading: false,
            tableData: [],
            currentItem: {},
            institutions: [],
            payType: [
                {
                    label: '电费',
                    value: 'ELECTRIC'
                },
                {
                    label: '水费',
                    value: 'WATER'
                },
                {
                    label: '燃气费',
                    value: 'GAS'
                }
            ],
            form: {
                home_no: '',
                chargeInst: '',
                sub_biz_type: 'ELECTRIC'
            },
            search: {
                type: '',
                status: '',
                keyword: ''
            },
            pagination: {
                current: 1,
                total: 1,
                limit: 10
            },
            columns: [
                {
                    title: '房源编号',
                    width: 140,
                    key: 'home_name'
                },
                {
                    title: '房源地址',
                    key: 'detail_address'
                },
                {
                    title: '缴费机构',
                    width: 180,
                    render: (h, p) => <span>{p.row.home_no && p.row.home_no.charge_inst_name}</span>
                },
                {
                    title: '户号',
                    width: 180,
                    render: (h, p) => <span>{p.row.home_no && p.row.home_no.home_no}</span>
                },
                {
                    title: '户号状态',
                    width: 140,
                    render: (h, p) => {
                        if (!p.row.home_no || !p.row.home_no.bind_status) {
                            return <span>未绑定</span>;
                        } else {
                            return <span>{p.row.home_no.bind_status === 1 ? '已绑定' : '不可绑定'}</span>;
                        }
                    }
                },
                {
                    title: '操作',
                    render: (h, p) => {
                        const status = !p.row.home_no ? 0 : p.row.home_no.bind_status;
                        const base = {
                            style: 'margin: 4px',
                            props: { size: 'small' }
                        };
                        return (
                            <div>
                                {this.roleId === 100 &&
                                    status === 0 && (
                                        <i-button {...base} onClick={() => this.handleBind(p.row)}>
                                            绑定户号
                                        </i-button>
                                    )}
                                {status === 1 && (
                                    <i-button {...base} onClick={() => this.billsDetail(p.row)}>
                                        查看历史缴费
                                    </i-button>
                                )}
                                {this.roleId === 100 &&
                                    status === 1 && (
                                        <i-button {...base} onClick={() => this.handleEdit(p.row)}>
                                            修改户号
                                        </i-button>
                                    )}
                                {this.roleId === 100 &&
                                    status === 0 && (
                                        <i-button {...base} onClick={() => this.handleFreeze(p.row)}>
                                            户号设为不可绑定
                                        </i-button>
                                    )}
                            </div>
                        );
                    }
                }
            ]
        };
    },
    /* eslint-enable */
  created () {
    this.initData()
  },
  methods: {
    async initData () {
      try {
        this.loading = true
        const { keyword } = this.search
        const { current: page, limit: page_size } = this.pagination
        const data = {
          keyword: keyword || null,
          page,
          page_size
        }
        const res = await http.req(api.agency_pay_homes, null, data)
        if (res) {
          this.pagination.total = res.count
          this.tableData = res.rows
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
    },
    async initInstitutions (homeId, subBizType = 'ELECTRIC') {
      try {
        this.loadingIns = true
        const res = await http.req(
          api.agency_pay_institutions,
          null,
          {
            page: 1,
            page_size: 1000,
            sub_biz_type: subBizType,
            home_id: homeId
          },
          true
        )
        if (res) {
          this.institutions = res.chargeInsts
        } else {
          this.$Message.error({
            content: '该房源所在门店或商户没有开通代缴功能',
            duration: 5
          })
          this.visible = false
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.loadingIns = false
      }
    },
    handleBizTypeChange (type) {
      this.form.chargeInst = ''
      this.initInstitutions(this.currentItem.id, type)
    },
    handleFreeze (item) {
      this.$Modal.confirm({
        loading: true,
        render: h => {
          return (
            <div>
              <h3 class="margin-bottom-20">
                <b>{`确定该房源[${item.detail_address}]无法绑定户号，进行电费代缴？`}</b>
              </h3>
              <div class="margin-bottom-10">常见无法绑定户号情况：</div>
              <ol style="padding-left: 20px;line-height:2">
                <li>房源为老旧小区无法进行网络缴纳电费</li>
                <li>当地电费收缴机构不支持网络缴纳电费</li>
              </ol>
            </div>
          )
        },
        onOk: () => {
          this.freeze(item.id, item.home_no)
        }
      })
    },
    async freeze (id) {
      try {
        const res = await http.req(api.agency_pay_forbidden, null, {
          home_id: id,
          sub_biz_type: 'ELECTRIC',
          bind_status: 2,
          biz_type: 'JF'
        })
        if (res) {
          this.$Message.success('设置成功')
          this.initData()
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.$Modal.remove()
      }
    },
    handleEdit (item) {
      this.openModal(item.id, item.home_no.sub_biz_type)
      this.currentItem = item
      this.form.home_no = item.home_no.home_no
      this.form.chargeInst = item.home_no.charge_inst
      this.form.sub_biz_type = item.home_no.sub_biz_type
      this.isEdit = true
    },
    handleBind (item) {
      this.currentItem = item
      this.openModal(item.id)
      this.isEdit = false
    },
    openModal (homeId, subBizType = 'ELECTRIC') {
      this.cleanModal()
      this.visible = true
      this.initInstitutions(homeId, subBizType)
    },
    cleanModal () {
      this.form.home_no = ''
      this.form.chargeInst = ''
      this.form.sub_biz_type = 'ELECTRIC'
    },
    async handleSubmit () {
      const { home_no, chargeInst, sub_biz_type } = this.form
      if (!home_no || !chargeInst) {
        this.$Message.error('请填写户号和选择缴费机构')
        return
      }
      try {
        this.submiting = true
        const selected = this.institutions.find(item => item.chargeInst === chargeInst)
        const data = {
          home_no,
          sub_biz_type,
          home_id: this.currentItem.id,
          charge_inst: chargeInst,
          charge_inst_name: selected.chargeInstName
        }
        const res = await http.req(api.agency_pay_bind, null, data)
        if (res) {
          this.$Message.success('绑定成功')
          this.visible = false
          this.initData()
        } else {
          this.submiting = false
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.submiting = false
      }
    },
    billsDetail (home) {
      this.currentHome = home
      this.billsVisible = true
    }
  }
}
</script>